﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using ZK.Common;
using ZK.Common.Log4;

namespace ZK.HardWareControl
{
    /// <summary>
    /// test connect include tcpip && serial port
    /// </summary>
    public class TestConnect
    {
        /// <summary>
        /// test tcpip
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="port"></param>
        public void Test(string ip, int port)
        {
            bool res = false;
            int seconds = Convert.ToInt32(AppConfigHelper.GetAppSettings("WebSocketTime"));
            System.Diagnostics.Stopwatch swThd = System.Diagnostics.Stopwatch.StartNew();
            IPAddress iPAddress = IPAddress.Parse(ip);
            IPEndPoint point = new IPEndPoint(iPAddress, port);
            using (Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp))
            {
                Task.Factory.StartNew(() =>
                {
                    try
                    {
                        sock.Connect(point);
                        res = true;
                    }
                    catch (Exception e)
                    {
                        LogManage.WriteErr("TestConnect Test " + ip + ":" + e.Message);
                    }
                }).Wait(seconds * 1000);
                sock.Close();
                if (!res) LogManage.WriteErr(ip + ":连接超时、ip端口不正确");
            }
        }
    }
}
